<template>
  <div class="console-panel h-full flex flex-col bg-gray-50">
    <!-- 主控制台区域 -->
    <div class="flex-1 bg-white border border-gray-200 rounded-lg m-4">
      <!-- 控制台头部信息 -->
      <div class="p-6 border-b border-gray-200">
        <div class="flex items-center justify-between mb-4">
          <div class="flex items-center">
            <!-- 控制台图标 -->
            <div class="w-12 h-12 rounded-full bg-purple-500 text-white flex items-center justify-center text-xl font-bold mr-4">
              <el-icon><iEpMonitor /></el-icon>
            </div>
            <div>
              <h2 class="text-xl font-semibold text-gray-800 mb-1">控制台</h2>
              <p class="text-sm text-gray-500">交互式命令行界面，执行脚本和调试命令</p>
            </div>
          </div>
          
          <!-- 控制台状态和操作按钮 -->
          <div class="flex items-center space-x-4">
            <div class="flex items-center">
              <span class="text-sm text-gray-500 mr-2">控制台状态:</span>
              <el-tag 
                :type="isEnabled ? 'success' : 'danger'" 
                size="default"
                class="px-3 py-1"
              >
                {{ isEnabled ? '已启用' : '已禁用' }}
              </el-tag>
            </div>
            
            <div class="flex items-center space-x-2">
              <el-button type="primary" size="default" @click="clearConsole">
                <el-icon class="mr-1"><iEpDelete /></el-icon>
                清空控制台
              </el-button>
              <el-button 
                :type="isEnabled ? 'warning' : 'success'" 
                size="default" 
                @click="toggleConsole"
              >
                <el-icon class="mr-1"><iEpSwitch /></el-icon>
                {{ isEnabled ? '禁用控制台' : '启用控制台' }}
              </el-button>
            </div>
          </div>
        </div>
        
        <!-- 控制台信息 -->
        <div class="flex items-center justify-between">
          <div class="flex items-center space-x-4">
            <div class="flex items-center">
              <span class="text-sm text-gray-500 mr-2">版本:</span>
              <el-tag size="small" type="info">ScriptVue Console v1.0.0</el-tag>
            </div>
            
            <div class="flex items-center">
              <span class="text-sm text-gray-500 mr-2">命令历史:</span>
              <span class="text-sm font-semibold text-blue-600">{{ commandHistory.length }}</span>
            </div>
          </div>
          
          <div class="flex items-center space-x-2">
            <el-button size="default" @click="showHelp">
              <el-icon class="mr-1"><iEpQuestionFilled /></el-icon>
              帮助
            </el-button>
            <el-button size="default" @click="exportHistory">
              <el-icon class="mr-1"><iEpDownload /></el-icon>
              导出历史
            </el-button>
          </div>
        </div>
      </div>

      <!-- 控制台内容区域 -->
      <div class="p-6">
        <div 
          ref="consoleContainer"
          class="console-content bg-gray-900 text-green-400 p-4 rounded-lg font-mono text-sm h-96 overflow-auto"
          :class="{ 'opacity-50': !isEnabled }"
        >
          <!-- 欢迎信息 -->
          <div v-if="history.length === 0" class="welcome-section">
            <div class="py-4">
              <div class="w-16 h-16 mb-4 bg-gray-700 rounded-full flex items-center justify-center">
                <el-icon class="text-2xl text-gray-400"><iEpMonitor /></el-icon>
              </div>
              <h3 class="text-lg font-semibold text-green-400 mb-2">ScriptVue Console v1.0.0</h3>
              <p class="text-gray-400 mb-4">Type 'help' for available commands.</p>
              
              <div class="text-left">
                <div class="text-blue-400 mb-3 font-semibold">Available commands:</div>
                <div class="space-y-2 text-sm">
                  <div class="flex items-center text-gray-300">
                    <span class="w-2 h-2 bg-green-400 rounded-full mr-3"></span>
                    <span><span class="text-green-400">help</span> - 显示帮助信息</span>
                  </div>
                  <div class="flex items-center text-gray-300">
                    <span class="w-2 h-2 bg-blue-400 rounded-full mr-3"></span>
                    <span><span class="text-green-400">clear</span> - 清空控制台</span>
                  </div>
                  <div class="flex items-center text-gray-300">
                    <span class="w-2 h-2 bg-yellow-400 rounded-full mr-3"></span>
                    <span><span class="text-green-400">run</span> - 运行当前脚本</span>
                  </div>
                  <div class="flex items-center text-gray-300">
                    <span class="w-2 h-2 bg-red-400 rounded-full mr-3"></span>
                    <span><span class="text-green-400">stop</span> - 停止执行</span>
                  </div>
                  <div class="flex items-center text-gray-300">
                    <span class="w-2 h-2 bg-purple-400 rounded-full mr-3"></span>
                    <span><span class="text-green-400">status</span> - 查看执行状态</span>
                  </div>
                  <div class="flex items-center text-gray-300">
                    <span class="w-2 h-2 bg-indigo-400 rounded-full mr-3"></span>
                    <span><span class="text-green-400">steps</span> - 显示步骤列表</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 历史记录 -->
          <div v-else class="history-section space-y-2">
            <div 
              v-for="(item, index) in history" 
              :key="index" 
              class="console-entry p-2 rounded transition-all duration-200 hover:bg-gray-800"
            >
              <div v-if="item.type === 'command'" class="flex items-center">
                <span class="text-green-400 mr-3 font-bold">></span>
                <span class="text-white font-medium">{{ item.content }}</span>
                <span class="text-gray-500 text-xs ml-auto">{{ formatTime(item.timestamp) }}</span>
              </div>
              <div v-else-if="item.type === 'output'" class="text-blue-300 ml-6 flex items-start">
                <span class="w-2 h-2 bg-blue-400 rounded-full mr-3 mt-2 flex-shrink-0"></span>
                <span class="flex-1">{{ item.content }}</span>
              </div>
              <div v-else-if="item.type === 'error'" class="text-red-400 ml-6 flex items-start">
                <span class="w-2 h-2 bg-red-400 rounded-full mr-3 mt-2 flex-shrink-0"></span>
                <span class="flex-1">{{ item.content }}</span>
              </div>
              <div v-else-if="item.type === 'info'" class="text-yellow-300 ml-6 flex items-start">
                <span class="w-2 h-2 bg-yellow-400 rounded-full mr-3 mt-2 flex-shrink-0"></span>
                <span class="flex-1">{{ item.content }}</span>
              </div>
            </div>
          </div>

          <!-- 命令输入行 -->
          <div v-if="isEnabled" class="command-input-section mt-4 pt-4 border-t border-gray-700">
            <div class="flex items-center">
              <span class="text-green-400 mr-3 font-bold text-lg">></span>
              <input 
                ref="commandInput"
                v-model="currentCommand"
                class="flex-1 bg-transparent border-none outline-none text-white font-mono text-sm"
                @keydown.enter="executeCommand"
                @keydown.up="navigateHistory(-1)"
                @keydown.down="navigateHistory(1)"
                placeholder="输入命令..."
              />
              <span v-if="!currentCommand" class="text-gray-500 animate-pulse text-lg">_</span>
            </div>
          </div>
          
          <div v-else class="text-gray-500 py-8">
            <div class="w-12 h-12 mb-3 bg-gray-700 rounded-full flex items-center justify-center">
              <el-icon class="text-xl text-gray-400"><iEpSwitch /></el-icon>
            </div>
            <p class="text-lg font-semibold">控制台已禁用</p>
            <p class="text-sm">点击"启用控制台"按钮来激活交互功能</p>
          </div>
        </div>
      </div>

      <!-- 底部状态栏 -->
      <div class="p-6 border-t border-gray-200 bg-gray-50 flex justify-between items-center">
        <div class="flex items-center space-x-4">
          <span class="text-sm text-gray-600">
            历史记录: <span class="font-semibold text-purple-600">{{ history.length }}</span> 条
          </span>
          <span class="text-sm text-gray-600">
            命令历史: <span class="font-semibold text-blue-600">{{ commandHistory.length }}</span> 条
          </span>
          <span v-if="executionStore.isRunning" class="text-sm text-green-600 flex items-center">
            <el-icon class="mr-1 animate-spin"><iEpLoading /></el-icon>
            脚本执行中...
          </span>
        </div>
        
        <div class="flex items-center space-x-2">
          <el-button size="small" @click="scrollToTop">
            <el-icon class="mr-1"><iEpArrowUp /></el-icon>
            顶部
          </el-button>
          <el-button size="small" @click="scrollToBottom">
            <el-icon class="mr-1"><iEpArrowDown /></el-icon>
            底部
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue'
import { useScriptStore } from '../stores/script'
import { useExecutionStore } from '../stores/execution'
import { 
  Delete as iEpDelete,
  Switch as iEpSwitch,
  Monitor as iEpMonitor,
  QuestionFilled as iEpQuestionFilled,
  Download as iEpDownload,
  Loading as iEpLoading,
  ArrowUp as iEpArrowUp,
  ArrowDown as iEpArrowDown
} from '@element-plus/icons-vue'

const scriptStore = useScriptStore()
const executionStore = useExecutionStore()

const consoleContainer = ref(null)
const commandInput = ref(null)

// 响应式数据
const isEnabled = ref(true)
const currentCommand = ref('')
const history = ref([])
const commandHistory = ref([])
const historyIndex = ref(-1)

// 生命周期
onMounted(() => {
  focusInput()
})

// 方法
const focusInput = () => {
  nextTick(() => {
    if (commandInput.value) {
      commandInput.value.focus()
    }
  })
}

const scrollToBottom = () => {
  nextTick(() => {
    if (consoleContainer.value) {
      consoleContainer.value.scrollTop = consoleContainer.value.scrollHeight
    }
  })
}

const addToHistory = (type, content) => {
  history.value.push({ type, content, timestamp: new Date() })
  scrollToBottom()
}

const executeCommand = () => {
  const command = currentCommand.value.trim()
  if (!command) return

  // 添加到历史记录
  commandHistory.value.unshift(command)
  if (commandHistory.value.length > 50) {
    commandHistory.value.pop()
  }
  historyIndex.value = -1

  // 显示命令
  addToHistory('command', command)
  
  // 执行命令
  processCommand(command)
  
  // 清空输入
  currentCommand.value = ''
}

const processCommand = (command) => {
  const [cmd, ...args] = command.split(' ')
  
  switch (cmd.toLowerCase()) {
    case 'help':
      addToHistory('output', 'Available commands:')
      addToHistory('info', '• clear - 清空控制台')
      addToHistory('info', '• run - 运行当前脚本')
      addToHistory('info', '• stop - 停止执行')
      addToHistory('info', '• status - 查看执行状态')
      addToHistory('info', '• steps - 显示步骤列表')
      break
      
    case 'clear':
      clearConsole()
      break
      
    case 'run':
      addToHistory('output', '开始执行脚本...')
      // TODO: 集成实际的执行逻辑
      break
      
    case 'stop':
      addToHistory('output', '停止执行')
      // TODO: 集成停止逻辑
      break
      
    case 'status':
      const status = executionStore.isRunning ? '执行中' : '就绪'
      addToHistory('output', `当前状态: ${status}`)
      addToHistory('info', `步骤总数: ${scriptStore.stepCount}`)
      break
      
    case 'steps':
      if (scriptStore.stepCount === 0) {
        addToHistory('info', '没有可用的步骤')
      } else {
        addToHistory('output', `共有 ${scriptStore.stepCount} 个步骤:`)
        scriptStore.steps.forEach(step => {
          addToHistory('info', `${step.stepNumber}. ${step.description}`)
        })
      }
      break
      
    default:
      addToHistory('error', `未知命令: ${cmd}`)
      addToHistory('info', "输入 'help' 查看可用命令")
  }
}

const navigateHistory = (direction) => {
  if (commandHistory.value.length === 0) return
  
  const newIndex = historyIndex.value + direction
  if (newIndex >= -1 && newIndex < commandHistory.value.length) {
    historyIndex.value = newIndex
    currentCommand.value = historyIndex.value === -1 ? '' : commandHistory.value[historyIndex.value]
  }
}

const clearConsole = () => {
  history.value = []
}

const toggleConsole = () => {
  isEnabled.value = !isEnabled.value
  if (isEnabled.value) {
    focusInput()
  }
}

// 新增方法
const showHelp = () => {
  addToHistory('output', 'Available commands:')
  addToHistory('info', '• clear - 清空控制台')
  addToHistory('info', '• run - 运行当前脚本')
  addToHistory('info', '• stop - 停止执行')
  addToHistory('info', '• status - 查看执行状态')
  addToHistory('info', '• steps - 显示步骤列表')
}

const exportHistory = () => {
  const historyText = history.value.map(item => {
    const timestamp = formatTime(item.timestamp)
    const prefix = item.type === 'command' ? '>' : '  '
    return `[${timestamp}] ${prefix}${item.content}`
  }).join('\n')
  
  const blob = new Blob([historyText], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `console-history-${Date.now()}.txt`
  a.click()
  URL.revokeObjectURL(url)
}

const scrollToTop = () => {
  if (consoleContainer.value) {
    consoleContainer.value.scrollTop = 0
  }
}

const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 暴露方法
defineExpose({
  addToHistory,
  clearConsole,
  focusInput
})
</script>

<style scoped>
.console-panel {
  font-family: 'Inter', 'SF Pro Display', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

/* 控制台内容区域样式 */
.console-content {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Courier New', monospace;
  line-height: 1.6;
  text-align: left;
}

.console-entry {
  border-left: 3px solid transparent;
  transition: all 0.2s ease;
}

.console-entry:hover {
  border-left-color: #10b981;
  background: rgba(16, 185, 129, 0.05);
}

/* 命令输入样式 */
.command-input-section {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  padding: 12px;
}

input {
  caret-color: #10b981;
  font-size: 14px;
}

input::placeholder {
  color: #6b7280;
}

input:focus {
  outline: none;
}

/* 欢迎区域样式 */
.welcome-section {
  background: linear-gradient(135deg, #1f2937, #374151);
  border-radius: 12px;
  border: 2px dashed #4b5563;
  text-align: left;
}

/* 滚动条样式 */
.console-content::-webkit-scrollbar {
  width: 6px;
}

.console-content::-webkit-scrollbar-track {
  background: #1f2937;
  border-radius: 3px;
}

.console-content::-webkit-scrollbar-thumb {
  background: #4b5563;
  border-radius: 3px;
}

.console-content::-webkit-scrollbar-thumb:hover {
  background: #6b7280;
}

/* 按钮样式增强 */
:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.2s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 6px;
  font-weight: 500;
}

/* 命令提示点样式 */
.command-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  display: inline-block;
  margin-right: 8px;
  flex-shrink: 0;
}

/* 历史记录样式 */
.history-section {
  max-height: 300px;
  overflow-y: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .console-panel .flex.space-x-4 {
    flex-direction: column;
    gap: 1rem;
  }
  
  .console-panel .flex.justify-between {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
  
  .console-content {
    height: 250px !important;
  }
}

/* 动画效果 */
@keyframes pulse-dot {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

.animate-pulse {
  animation: pulse-dot 1.5s ease-in-out infinite;
}

/* 命令高亮 */
.command-highlight {
  background: rgba(16, 185, 129, 0.1);
  border-radius: 4px;
  padding: 2px 4px;
  font-weight: 600;
}
</style>
